#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
校准测量次数计算器
根据频率范围、步进值、衰减范围等参数计算总测量次数和预估时长
"""

import math

class CalibrationCalculator:
    """校准计算器类"""
    
    def __init__(self):
        # 每次测量的基础时间消耗 (秒)
        self.measurement_time_per_point = 0.5  # 基础测量时间
        self.instrument_setup_time = 0.2       # 仪器设置时间
        self.attenuation_switching_time = 0.3  # 衰减器切换时间
        self.frequency_switching_time = 0.1    # 频率切换时间
        
    def calculate_measurement_count(self, start_freq, stop_freq, step_freq, 
                                   start_att, stop_att, step_att, specify_frequency_enabled=False):
        """
        计算总测量次数
        
        Args:
            start_freq: 起始频率 (MHz)
            stop_freq: 结束频率 (MHz) 
            step_freq: 频率步进 (MHz)
            start_att: 起始衰减 (dB)
            stop_att: 结束衰减 (dB)
            step_att: 衰减步进 (dB)
            specify_frequency_enabled: 是否启用指定频率
            
        Returns:
            dict: 包含测量次数和相关信息的字典
        """
        # 计算常规频率点数
        regular_freq_points = int((stop_freq - start_freq) / step_freq) + 1
        
        # 如果启用指定频率，计算特殊频率点数
        if specify_frequency_enabled:
            try:
                # 导入frequencies模块获取特殊频率
                from frequencies import all_frequencies
                
                # 筛选在测试范围内的特殊频率点
                special_frequencies = [
                    freq for freq in all_frequencies 
                    if start_freq <= freq <= stop_freq
                ]
                
                # 生成常规频率列表
                regular_frequencies = []
                current = start_freq
                while current <= stop_freq:
                    regular_frequencies.append(current)
                    current += step_freq
                
                # 合并并去重
                combined_frequencies = list(set(regular_frequencies + special_frequencies))
                freq_points = len(combined_frequencies)
                
                special_count = len(special_frequencies)
                
            except ImportError:
                # 如果无法导入frequencies模块，使用常规频率
                freq_points = regular_freq_points
                special_count = 0
        else:
            freq_points = regular_freq_points
            special_count = 0
        
        # 计算衰减点数
        att_points = int((stop_att - start_att) / step_att) + 1
        
        # 总测量次数
        total_measurements = freq_points * att_points
        
        # 计算时间估算
        time_estimation = self._estimate_time(freq_points, att_points)
        
        result = {
            'frequency_points': freq_points,
            'attenuation_points': att_points,
            'total_measurements': total_measurements,
            'frequency_range': (start_freq, stop_freq, step_freq),
            'attenuation_range': (start_att, stop_att, step_att),
            'time_estimation': time_estimation,
            'specify_frequency_enabled': specify_frequency_enabled
        }
        
        # 如果启用指定频率，添加相关信息
        if specify_frequency_enabled:
            result['regular_freq_points'] = regular_freq_points
            result['special_freq_points'] = special_count
        
        return result
    
    def _estimate_time(self, freq_points, att_points):
        """
        估算校准时间
        
        Args:
            freq_points: 频率点数
            att_points: 衰减点数
            
        Returns:
            dict: 时间估算信息
        """
        # 基础测量时间
        measurement_time = freq_points * att_points * self.measurement_time_per_point
        
        # 仪器设置时间 (每个频率点都需要设置)
        setup_time = freq_points * att_points * self.instrument_setup_time
        
        # 衰减器切换时间 (每个衰减值切换一次)
        att_switch_time = att_points * self.attenuation_switching_time
        
        # 频率切换时间 (每个频率点切换一次，乘以衰减点数)
        freq_switch_time = freq_points * att_points * self.frequency_switching_time
        
        # 总时间
        total_time_seconds = measurement_time + setup_time + att_switch_time + freq_switch_time
        
        # 添加10%的缓冲时间
        total_time_seconds *= 1.1
        
        # 转换为不同时间单位
        minutes = total_time_seconds / 60
        hours = minutes / 60
        
        return {
            'total_seconds': round(total_time_seconds, 1),
            'total_minutes': round(minutes, 1),
            'total_hours': round(hours, 2),
            'breakdown': {
                'measurement': round(measurement_time, 1),
                'setup': round(setup_time, 1),
                'attenuation_switching': round(att_switch_time, 1),
                'frequency_switching': round(freq_switch_time, 1)
            }
        }
    
    def format_time_estimation(self, time_info):
        """
        格式化时间估算信息
        
        Args:
            time_info: 时间信息字典
            
        Returns:
            str: 格式化的时间字符串
        """
        seconds = time_info['total_seconds']
        minutes = time_info['total_minutes']
        hours = time_info['total_hours']
        
        if hours >= 1:
            return f"{hours:.1f} 小时 ({minutes:.0f} 分钟)"
        elif minutes >= 1:
            return f"{minutes:.0f} 分钟 ({seconds:.0f} 秒)"
        else:
            return f"{seconds:.0f} 秒"
    
    def generate_report(self, calculation_result):
        """
        生成详细的校准报告
        
        Args:
            calculation_result: 计算结果字典
            
        Returns:
            str: 格式化的报告字符串
        """
        freq_points = calculation_result['frequency_points']
        att_points = calculation_result['attenuation_points']
        total = calculation_result['total_measurements']
        freq_range = calculation_result['frequency_range']
        att_range = calculation_result['attenuation_range']
        time_info = calculation_result['time_estimation']
        
        report = f"""
📊 校准测量计划报告
{'='*50}

📏 频率设置:
   起始频率: {freq_range[0]} MHz
   结束频率: {freq_range[1]} MHz  
   频率步进: {freq_range[2]} MHz
   频率点数: {freq_points} 个

🔧 衰减设置:
   起始衰减: {att_range[0]} dB
   结束衰减: {att_range[1]} dB
   衰减步进: {att_range[2]} dB
   衰减点数: {att_points} 个

📈 测量统计:
   总测量次数: {total:,} 次
   测量矩阵: {freq_points} × {att_points}

⏱️ 时间估算:
   预估总时长: {self.format_time_estimation(time_info)}
   
   详细分解:
   - 基础测量: {time_info['breakdown']['measurement']:.1f} 秒
   - 仪器设置: {time_info['breakdown']['setup']:.1f} 秒  
   - 衰减切换: {time_info['breakdown']['attenuation_switching']:.1f} 秒
   - 频率切换: {time_info['breakdown']['frequency_switching']:.1f} 秒

💡 说明:
   - 时间估算包含10%缓冲
   - 实际时间可能因网络延迟和仪器响应而有所变化
   - 大型校准建议分段进行
"""
        return report

def demo_calculation():
    """演示计算功能"""
    calculator = CalibrationCalculator()
    
    # 示例参数（使用默认界面值）
    start_freq = 30      # MHz
    stop_freq = 6000     # MHz  
    step_freq = 100      # MHz
    
    start_att = 0        # dB
    stop_att = 90        # dB
    step_att = 5         # dB
    
    print("🔍 校准测量次数计算演示")
    print("="*60)
    
    # 计算结果
    result = calculator.calculate_measurement_count(
        start_freq, stop_freq, step_freq,
        start_att, stop_att, step_att
    )
    
    # 生成报告
    report = calculator.generate_report(result)
    print(report)
    
    # 不同配置的对比
    print("\n📋 不同配置对比:")
    print("-"*40)
    
    configs = [
        ("快速测试", 30, 1000, 500, 0, 30, 10),
        ("标准测试", 30, 3000, 200, 0, 60, 10), 
        ("完整测试", 30, 6000, 100, 0, 90, 5),
        ("精细测试", 30, 6000, 50, 0, 90, 2.5),
    ]
    
    for name, sf, ef, step_f, sa, ea, step_a in configs:
        result = calculator.calculate_measurement_count(sf, ef, step_f, sa, ea, step_a)
        time_str = calculator.format_time_estimation(result['time_estimation'])
        print(f"{name:>8}: {result['total_measurements']:>6,} 次测量, 预估 {time_str}")

if __name__ == "__main__":
    demo_calculation()